package com.liuzhiqiang.shiro.token.controller;

import com.liuzhiqiang.shiro.token.config.Token;
import com.liuzhiqiang.shiro.token.config.UserExt;
import com.liuzhiqiang.shiro.token.vo.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class LoginController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest httpServletRequest;

    @PostMapping("/login")
    public AjaxResult login(String username, String password) {
        UserExt userExt = new UserExt();
        userExt.setUsername(username);
        userExt.setPassword("123456");
        userExt.setRoleId("1");
        if (!StringUtils.equals(password, userExt.getPassword())) {
            throw new RuntimeException("密码不正确");
        }

        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token, userExt, 60 * 60 * 5, TimeUnit.SECONDS);
        Subject subject = SecurityUtils.getSubject();
        subject.login(new Token(token));


        return AjaxResult.successData(token);
    }

    @PostMapping("/logout")
    public AjaxResult logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        // 清除redis
        String token = httpServletRequest.getHeader("Authorization");
        redisTemplate.delete(token);
        return AjaxResult.success();
    }

}
